package cn.ljq.controller.adm;

import cn.ljq.dao.LargeFileMapper;
import cn.ljq.dao.UserMapper;
import cn.ljq.entity.Largefile;
import cn.ljq.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.OutputStream;

//公共的  不会被拦截
@Controller
@RequestMapping("/public")
public class PublicController {


    @Autowired
    UserMapper userMapper;

    @Autowired
    LargeFileMapper largeFileMapper;


    @RequestMapping("/main")  //显示登录页面
    public String daoMain(){

        return "main";

    }


    @RequestMapping("/login")  //登录操作
    public String login(Model model, String phone, String pwd, HttpServletRequest request){

        //如果登录成功

        System.out.println("登录那个人的账号：" + phone);

        System.out.println("登录的那个人的密码：" + pwd);

        HttpSession session = request.getSession();

        System.out.println("登录的 session id =" + session.getId());

        User user = userMapper.findByPhone(phone);

        System.out.println("找到那个人大数据：" + user);

        if (user == null){   //没找到这个人

            model.addAttribute("err","登录失败-账号不存在");

            return "/main";
        }

        if (pwd!=null && pwd.equals(user.getPwd())){   //密码不为空 并且 密码是对的

            //登陆成功  每个浏览器对应一个session对象

            user.setPwd("");  //把密码设置为空 防止被盗号

            session.setAttribute("DL",user);  //把登录人的信息带给浏览器 设置登录成功的标志

            model.addAttribute("err","登录成功");

            return "/main";
        }

        model.addAttribute("err","登录失败-密码错误");

        return "/main";
    }



    @RequestMapping("/logout")  //退出登录操作
    public String logout(HttpSession session,Model model){
        System.out.println("与退出登录，销毁对象");
        session.invalidate();
        model.addAttribute("err","已退出登录，请登录！！！");
        return "/main";
    }



    @GetMapping("/showimg/{uuid}")  //显示图片
    public void showimg(@PathVariable("uuid")String id , HttpServletResponse response)throws IOException {

        Largefile one = largeFileMapper.findPic(id);

        Object content = one.getContent();

        OutputStream os = response.getOutputStream();

        response.setContentType("images/jpeg");

        byte[] buf = (byte[])content;

        os.write(buf);

        os.flush();

    }




}
